package com.sc.web.spring;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Formatter;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.key.KeyGenerater;
import com.sc.util.key.SignProvider;

/**
 * 项目访问拦截器
 * @author maoyongbin
 * @日期 Jul 24, 2017 11:56:15 AM
 */
public class AccessInterceptor extends HandlerInterceptorAdapter {
	
	/**
	 * 拦截器处理
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//获取ip地址
		InetAddress address =InetAddress.getLocalHost();
		String ipAddr = address.getHostAddress();
		//获取mac地址
		byte[] mac = NetworkInterface.getByInetAddress(address).getHardwareAddress();
		String macAddr = ""; 	
        Formatter formatter = new Formatter(); 	//格式化
        for (int i = 0; i < mac.length; i++) { 
        	macAddr = formatter.format(Locale.getDefault(), "%02X%s", mac[i], 
        			(i < mac.length - 1) ? "-" : "").toString(); 

        }
        formatter.close();
        
        //生成公钥
  		KeyGenerater keyGenerater = new KeyGenerater();
  		keyGenerater.generater(ipAddr,macAddr,ConfigBeanAdapter.plain);
  		
  		//验证
  		boolean result = SignProvider.verify(keyGenerater.getPubKey(), ConfigBeanAdapter.plain, ConfigBeanAdapter.priSign.getBytes());
		
		return result;
	}
}
